package android.view

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.netease.core.R
import kotlinx.coroutines.script.Controller
import kotlinx.coroutines.script.tes.initializeApp
import kotlinx.coroutines.script.tes.printLog
import kotlinx.coroutines.script.tes.toast
import sample.ui.ConsoleLayout
import sample.ui.FloatControllerLayout

class WindowManagerService : Service() {
    override fun onBind(intent: Intent?): IBinder? = null
    private val channelTitleKey = "　"
    private val channelId by lazy {
        val key = channelTitleKey
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val c = NotificationChannel(
                key, key,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                setShowBadge(false)
                enableVibration(false)
                enableLights(false)
            }
            getSystemService(NotificationManager::class.java).createNotificationChannel(c)
        }
        key
    }

    private fun getNotification() = NotificationCompat.Builder(this, channelId).apply {
        setContentTitle(channelTitleKey)
        setContentText("正在运行")
        setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        val printIntent = Intent(this@WindowManagerService, WindowManagerService::class.java)
        printIntent.action = "NULL"
        val pi = PendingIntent.getService(this@WindowManagerService, 0, printIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
        setSmallIcon(R.mipmap.ic_launcher)
        val acb = NotificationCompat.Action.Builder(0, "正在运行", pi)
        addAction(acb.build())
        setSilent(true)
        setOngoing(true)
    }.build()

    private var screenStatusReceiver: BroadcastReceiver? = null
    private var volumeChangeReceiver: BroadcastReceiver? = null

    override fun onCreate() {
        super.onCreate()
        initializeApp(this,)
        printLog { "ServiceImpl onCreate" }
        val notification = getNotification()
        val notificationId = 5173
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            try {
                startForeground(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
            } catch (e: Throwable) {
                e.printStackTrace()
                stopSelf()
                return
            }
        } else {
            startForeground(notificationId, notification)
        }
        registerListenScreenOff()
        registerListenVolumeChange()
        ins = this

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        printLog { "ServiceImpl onStartCommand" }
//        ControllerLayout.initialize(this)
        FloatControllerLayout.Companion.initialize(this)
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        printLog { "ServiceImpl onDestroy" }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            stopForeground(STOP_FOREGROUND_REMOVE)
        }
        unregisterListenScreenOff()
        unregisterListenVolumeChange()
        ins = null

    }

    companion object {
        var ins: WindowManagerService? = null
        fun start(context: Context) {
//            ControllerLayout.notifyDisplay(true)
            FloatControllerLayout.Companion.notifyDisplay(true)
            ContextCompat.startForegroundService(
                context,
                Intent(context, WindowManagerService::class.java)
            )
        }

        fun stop(context: Context) {
//            ControllerLayout.notifyDisplay(false)
            FloatControllerLayout.Companion.notifyDisplay(false)
            context.stopService(Intent(context, WindowManagerService::class.java))
            toast("已关闭悬浮按钮")
        }
    }

    private fun registerListenScreenOff() {
        val intentFilter = IntentFilter()
            .also { it.addAction(Intent.ACTION_SCREEN_OFF) }
        val receiver = object: BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == Intent.ACTION_SCREEN_OFF) {
                    ConsoleLayout.Companion.markStoppedByScreenOff(true)
                    Controller.Companion.get().stop("")
                }
            }
        }
        screenStatusReceiver = receiver
        registerReceiver(receiver, intentFilter)
    }

    private fun unregisterListenScreenOff() {
        val receiver = screenStatusReceiver
        if (receiver != null) unregisterReceiver(receiver)
        screenStatusReceiver = null
    }

    private fun registerListenVolumeChange() {
        val intentFilter = IntentFilter()
            .also { it.addAction("android.media.VOLUME_CHANGED_ACTION") }
        val receiver = object: BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == "android.media.VOLUME_CHANGED_ACTION") {
                    FloatControllerLayout.Companion.notifyShow(true)
                }
            }
        }
        volumeChangeReceiver = receiver
        registerReceiver(receiver, intentFilter)
    }

    private fun unregisterListenVolumeChange() {
        val receiver = volumeChangeReceiver
        if (receiver != null) unregisterReceiver(receiver)
        volumeChangeReceiver = null
    }
}